package dao.Impl;

import dao.GenericDao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class GenericDaoImpl <T extends Serializable,ID extends Number> implements GenericDao<T,ID> {
    private SqlSession sqlSession;
    private String nameSpase;
    @Autowired
    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
    GenericDaoImpl(){
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        nameSpase = StringUtils.uncapitalize(clazz.getSimpleName());
    }
    private String getSqlStatement(String sqlId){
        return nameSpase.concat(".").concat(sqlId);
    }
    @Override
    public void create(T t) {
        sqlSession.insert(getSqlStatement("create"),t);
    }

    @Override
    public List<T> queryAll() {
        return sqlSession.selectList(getSqlStatement("queryAll"));
    }

    @Override
    public T queryById(ID id) {
        return sqlSession.selectOne(getSqlStatement("queryById"),id);
    }

    @Override
    public void modify(T t) {
        sqlSession.update("modify",t);
    }

    @Override
    public void remove(ID id) {
        sqlSession.delete(getSqlStatement("remove"),id);
    }

    @Override
    public void create(String sqlId, Object parameter) {
        sqlSession.insert(getSqlStatement(sqlId),parameter);
    }

    @Override
    public T queryOne(String sqlID, Object parameter) {
        return sqlSession.selectOne(getSqlStatement(sqlID),parameter);
    }

    @Override
    public void modify(String sqlId, Object parameter) {
        sqlSession.update(getSqlStatement(sqlId),parameter);
    }

    @Override
    public List<T> queryList(String sqlId, Object parameter) {
        return sqlSession.selectList(getSqlStatement(sqlId),parameter);
    }

    @Override
    public Object query(String sqlId, Object parameter) {
        return sqlSession.selectOne(getSqlStatement(sqlId),parameter);
    }
}
